package com.zut.edu.nfc;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.zut.edu.R;
import com.zut.edu.bean.Event;
import com.zut.edu.http.BaseCallback;
import com.zut.edu.http.OkhttpHelper;
import com.zut.edu.utils.StringUtils;
import com.zut.edu.utils.SystemTTSUtils;
import com.zut.edu.widget.CustomVideoView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class ReadTextActivity extends BaseNfcActivity implements View.OnClickListener{

    @BindView(R.id.stop_read_button)
    QMUIRoundButton stopreadbutton;
    @BindView(R.id.read_bg)
    CustomVideoView readbg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_readtext);
        ButterKnife.bind(this);
        QMUIStatusBarHelper.translucent(this);
        setListener();
        initBackground();
    }


    @Override
    public void onNewIntent(Intent intent) {
        //1.获取Tag对象
        super.onNewIntent(intent);
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] tagbytes = detectedTag.getId();    //获取16进制Tag的ID
        String mTagId = bytesToHexString(tagbytes);//16进制转字符串
        //2.获取Ndef的实例
        Ndef ndef = Ndef.get(detectedTag);
        readNfcTag(intent,mTagId);//读取readNfcTag，解析parseTextRecord，显示setTextView
    }

    /**
     * 读取NFC标签文本数据
     */
    private void readNfcTag(Intent intent,String mTagId) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                    NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msgs[] = null;
            int contentSize = 0;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                    contentSize += msgs[i].toByteArray().length;
                }
            }
            try {
                if (msgs != null) {
                    NdefRecord record = msgs[0].getRecords()[0];
                    String textRecord = parseTextRecord(record);
                    if(StringUtils.isEmpty(textRecord)){
                        postEvent(mTagId,"0");
                        SystemTTSUtils systemTTSUtils = new SystemTTSUtils();
                        systemTTSUtils.initTTS(this,"追溯失败");
                        Toast.makeText(ReadTextActivity.this,"追溯失败",Toast.LENGTH_SHORT).show();
                    }
                    else{
                        postEvent(mTagId,"1");
                        Intent showtextactivity = new Intent(ReadTextActivity.this,ShowTextActivity.class);
                        showtextactivity.putExtra("data",textRecord);
                        showtextactivity.putExtra("mTagId",mTagId);
                        startActivity(showtextactivity);

                    }

                }
            } catch (Exception e) {
                Log.e("RT",String.valueOf(e));
            }
        }
    }

    /**
     * 解析NDEF文本数据，从第三个字节开始，后面的文本数据
     *
     * @param ndefRecord
     * @return
     */
    public static String parseTextRecord(NdefRecord ndefRecord) {
        /**
         * 判断数据是否为NDEF格式
         */
        //判断TNF
        if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
            return null;
        }
        //判断可变的长度的类型
        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            return null;
        }
        try {
            //获得字节数组，然后进行分析
            byte[] payload = ndefRecord.getPayload();
            //下面开始NDEF文本数据第一个字节，状态字节
            //判断文本是基于UTF-8还是UTF-16的，取第一个字节"位与"上16进制的80，16进制的80也就是最高位是1，
            //其他位都是0，所以进行"位与"运算后就会保留最高位
            String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
            //3f最高两位是0，第六位是1，所以进行"位与"运算后获得第六位
            int languageCodeLength = payload[0] & 0x3f;
            //下面开始NDEF文本数据第二个字节，语言编码
            //获得语言编码
            String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
            //下面开始NDEF文本数据后面的字节，解析出文本
            String textRecord = new String(payload, languageCodeLength + 1,
                    payload.length - languageCodeLength - 1, textEncoding);
            return textRecord;
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }

    /**
     * 将16进制数据转字符串
     * @param src
     * @return
     */
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.toUpperCase(Character.forDigit(
                    (src[i] >>> 4) & 0x0F, 16));
            buffer[1] = Character.toUpperCase(Character.forDigit(src[i] & 0x0F,
                    16));
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }

    private void setListener(){
        stopreadbutton.setOnClickListener(this);
        stopreadbutton.setChangeAlphaWhenPress(true);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.stop_read_button:
                super.onBackPressed();
                break;
        }
    }

    private void initBackground() {
        readbg.setVideoURI(Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.read_bg));

        //播放
        readbg.start();
        //循环播放
        readbg.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
               readbg.start();
                mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        return false;
                    }
                });
            }
        });

    }
    //返回重启加载
    @Override
    protected void onRestart() {
        super.onRestart();
        initBackground();
    }

    private void postEvent(String tagId,String eventStatus){

        String userId = StringUtils.getLocalitem(this,"user","userId");
        String eventLocation = StringUtils.getLocalString(this,"location");

        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        Map<String,Object> params = new HashMap<>(5);
        params.put("tagId",tagId);
        params.put("userId",userId);
        params.put("eventDate",StringUtils.currentTime());
        params.put("eventLocation",eventLocation);
        params.put("eventStatus",eventStatus);
        okhttpHelper.post(StringUtils.BASE_URL+"/event/add", params, new BaseCallback<Event>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("onFailure", String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Event event, int code) throws IOException {
                Log.e("onSuccess", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
            }


            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("onError", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
            }
        });
    }

}
